package cn.itcast.controller;

import cn.itcast.client.UserClicent;
import cn.itcast.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/consumer")
//@DefaultProperties(defaultFallback = "queryUserFallback")
public class ConsumerController {
//    @Autowired
//    RestTemplate restTemplate;

     @Autowired
    UserClicent userClicent;

    /**
     * 此处三种访问服务的方式，前一二种不为动态，当在启动类上加上了 @LoadBalanced后就可以用restTemplate进行动态访问
     * @return
     */
//1    @Autowired
//1    private DiscoveryClient discoveryClient;

//2    @Autowired
//2    private RibbonLoadBalancerClient client;
    @GetMapping("findOne1")
    //返回值类型，参数列表要一样
    /**
     * 超时设置第一种，第二种是在配置文件里加入hystrix:
     *   commamd:
     *     default:
     *       execution:
     *         isolation:
     *           thread:
     *             timeoutInMilliseconds: 3000
     *     user-service:
     *       execution:
     *         isolation:
     *           thread:
     *             timeoutInMilliseconds: 3000
     *             这样就可以设置为全局设置，也可以设置单独的一个服务的超时设置
     */
    //@HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value ="5000" )})
    public User queryUser() {

//        Map<String,Map<String,ServiceInstance>>
        //2ServiceInstance instances = client.choose("user-service");
        //1 List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //1 ServiceInstance serviceInstance = instances.get(0);
        //1 serviceInstance.getHost();
        //1 String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/findOne";


        //id+路径id:user-service,就是注册到eureka里的ID
       // String url="http://user-service/user/findOne";
        //(url, String.class)这里选择的是String类型，也可以换成对象类型user，这个时候就要有对应的实体类
        //String forObject = restTemplate.getForObject(url, String.class);
        //System.out.println("user:"+forObject);
        User user = userClicent.queryAll();
        System.out.println("user:"+user);
        return user;
    }

    public String queryUserFallback(){
        return "不好意思，服务器太拥挤了";
    }
}
